package com.xindaoapp.happypet.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.circle.library.CircularProgressButton;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.MyPostListAdapter2;
import com.xindaoapp.happypet.adapter.MyPostListAdapter2.OnNextPageListener;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.protocol.IUploadProgress;
import com.xindaoapp.happypet.protocol.PostQueue;
import com.xindaoapp.happypet.ui.BaseFragment;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.KeyValuePair;

/**
 * 我的发帖
 * 
 * @author xindaoapp
 * 
 */
public class MyPostFragment extends BaseFragment {
    public static Fragment newInstance(boolean isBack) {
        Fragment fragment = new MyPostFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(Constants.KEY_IS_CLICK_TO_BACK, isBack);
        fragment.setArguments(bundle);
        return fragment;
    }

    private PullToRefreshListView vPullToRefreshListView;
    private MyPostListAdapter2 mAdapter2;
    /** 顶部发表进度条 */
    private LinearLayout vTopUnPublishContainer;

    private RefreshBroadCast refreshBroadCast;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        refreshBroadCast = new RefreshBroadCast();
        getActivity().registerReceiver(refreshBroadCast,
                new IntentFilter(Constants.REFRESHPOSTINFO));
        View rootView = inflater.inflate(R.layout.layout_listview, container, false);
        vPullToRefreshListView = (PullToRefreshListView) rootView.findViewById(R.id.listview);
        vPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        vPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadDatas();
            }
        });
        vPullToRefreshListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Message info = (Message) parent.getAdapter().getItem(position);
                if (getArguments().getBoolean(Constants.KEY_IS_CLICK_TO_BACK)) {
                    Intent data = new Intent();
                    data.putExtra(Constants.KEY_POST_NAME, info.subject);
                    data.putExtra(Constants.KEY_POST_TID, info.tid);
                    if (info.pics.size() > 0) {
                        data.putExtra(Constants.KEY_POST_COVER, info.pics.get(0).url);
                    }
                    getActivity().setResult(Activity.RESULT_OK, data);
                    getActivity().finish();
                } else {// 跳转详情
                    Intent intent = new Intent(mContext, PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, info.tid);
                    mContext.startActivity(intent);
                }
            }
        });
        if (!getArguments().getBoolean(Constants.KEY_IS_CLICK_TO_BACK)) {
            // initListHeaderView();
        }
    }

    private void initListHeaderView() {
        vPullToRefreshListView.getRefreshableView().addHeaderView(getHeaderView(getMyPostQueue()));
        vPullToRefreshListView
                .setAdapter(mAdapter2 =
                        new MyPostListAdapter2(getActivity(), new ArrayList<Message>(),
                                Constants.PAGE_SIZE, R.layout.activity_my_club_item,
                                R.layout.item_loading));
    }

    @Override
    protected void loadDatas() {
        super.loadDatas();
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getMyPost(UserState.getUserUid(), Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                        new IRequest<List<Message>>() {

                            @Override
                            public void request(List<Message> t) {
                                if (null != t) {
                                    onDataArrived(true);
                                    if (t.size() == 0) {
                                        onDataArrivedEmpty();
                                    } else {
                                        vPullToRefreshListView.setAdapter(mAdapter2 =
                                                new MyPostListAdapter2(getActivity(), t,
                                                        Constants.PAGE_SIZE,
                                                        R.layout.activity_my_club_item,
                                                        R.layout.item_loading));
                                        mAdapter2.setOnNextPageListener(mOnNextPageListener);
                                    }
                                } else {
                                    onDataArrived(false);
                                }
                                vPullToRefreshListView.onRefreshComplete();
                            }
                        });
    }

    OnNextPageListener mOnNextPageListener = new OnNextPageListener() {

        @Override
        public void nextPage(int start, int size, final ILoadNextPageData<Message> iLoadNextPageData) {
            HappyPetApplication.get().getMoccaApi()
                    .getMyPost(UserState.getUserUid(), start, size, new IRequest<List<Message>>() {

                        @Override
                        public void request(List<Message> t) {
                            iLoadNextPageData.loadNextPageData(t);
                        }
                    });
        }
    };

    /**
     * 我的发表队列
     * 
     * @return
     */
    private List<PostQueue> getMyPostQueue() {
        List<PostQueue> postQueueImpls = new ArrayList<PostQueue>();
        // 解析队列里面数据是发表还是回复
        for (int i = 0; i < HappyPetApplication.get().getUploaQueueImpl().getPostQueue().size(); i++) {
            if (TextUtils.isEmpty(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                    .get(i).getPostInfo().tid)) {
                postQueueImpls.add(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                        .get(i));
            }
        }

        return postQueueImpls;
    }

    /**
     * 我的回复队列
     * 
     * @return
     */
    private List<PostQueue> getMyReplyQueue() {
        List<PostQueue> postQueueImpls = new ArrayList<PostQueue>();
        // 解析队列里面数据是发表还是回复
        for (int i = 0; i < HappyPetApplication.get().getUploaQueueImpl().getPostQueue().size(); i++) {
            if (!TextUtils.isEmpty(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                    .get(i).getPostInfo().tid)) {
                postQueueImpls.add(HappyPetApplication.get().getUploaQueueImpl().getPostQueue()
                        .get(i));
            }
        }
        return postQueueImpls;
    }

    /**
     * 获取需要重新提交的队列
     * 
     * @param list
     * @return
     */
    private View getHeaderView(List<PostQueue> list) {
        if (vTopUnPublishContainer == null) {
            vTopUnPublishContainer =
                    (LinearLayout) View.inflate(getActivity(), R.layout.layout_top_post, null);
        }
        vTopUnPublishContainer.removeAllViews();
        holders = new ViewHolder[list.size()];
        for (int i = 0; i < list.size(); i++) {
            final PostQueue info = list.get(i);
            final View item = View.inflate(getActivity(), R.layout.item_top_post, null);
            holders[i] = new ViewHolder();
            holders[i].icon = (ImageView) item.findViewById(R.id.icon);
            if (null != info.getSendingInfo() && info.getSendingInfo().second == 0) {
                ImageLoader.getInstance().displayImage("file://" + info.getSendingInfo().first,
                        holders[i].icon);
            } else if (null != info.getSendingInfo() && info.getSendingInfo().second == 1) {
                ImageLoader.getInstance().displayImage("file://" + info.getPostInfo().videoCover,
                        holders[i].icon);
            } else if (info.getPostInfo().sendingArray.size() > 0) {
                KeyValuePair<String, Integer> pair = info.getPostInfo().sendingArray.get(0);
                if (pair.second == 0) {
                    ImageLoader.getInstance().displayImage("file://" + pair.first, holders[i].icon);
                } else if (pair.second == 1) {
                    ImageLoader.getInstance().displayImage(
                            "file://" + info.getPostInfo().videoCover, holders[i].icon);
                }
            }
            holders[i].plan = (TextView) item.findViewById(R.id.plan);
            holders[i].name = (TextView) item.findViewById(R.id.name);
            holders[i].btnUpload = (ImageView) item.findViewById(R.id.btn_upload);
            holders[i].progressBar = (CircularProgressButton) item.findViewById(R.id.progress);
            holders[i].container = item.findViewById(R.id.r_top);
            holders[i].name.setText(TextUtils.isEmpty(info.getPostInfo().title) ? info
                    .getPostInfo().content : info.getPostInfo().title);
            if (info.isRunning()) {// 如果是正在发帖，则添加监听器
                info.addListener(new uploadProgress(info, holders[i]));
                holders[i].progressBar.setProgress(1);
                resetSendState(holders[i], true);
            } else {
                resetSendState(holders[i], false);
            }

            final int temp = i;
            holders[i].btnUpload.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    resetSendState(holders[temp], true);
                    info.start(new uploadProgress(info, holders[temp]));
                }
            });
            vTopUnPublishContainer.addView(item);
        }
        return vTopUnPublishContainer;
    }

    private void resetSendState(ViewHolder holder, boolean isSending) {
        if (isSending) {
            holder.btnUpload.setEnabled(false);
            holder.btnUpload.setImageResource(R.drawable.btn_uploading);
        } else {
            holder.btnUpload.setEnabled(true);
            holder.btnUpload.setImageResource(R.drawable.btn_upload_android);
        }
    }

    class uploadProgress implements IUploadProgress {
        ViewHolder holder;
        PostQueue info;

        public uploadProgress(PostQueue info, ViewHolder holder) {
            super();
            this.holder = holder;
            this.info = info;
        }

        @Override
        public void success() {
            getHeaderView(getMyPostQueue());
            // onLoadDatas();
            loadDatas();
        }

        @Override
        public void start(int current, int count) {
            if (count == 0) {
                holder.plan.setText(String.format("正在发送...", current, count));
            } else {
                holder.plan.setText(String.format("正在发送：%s / %s", current, count));
                KeyValuePair<String, Integer> pair =
                        info.getPostInfo().sendingArray.get(current - 1);
                if (pair.second == 0) {
                    ImageLoader.getInstance().displayImage("file://" + pair.first, holder.icon);
                } else if (pair.second == 1) {
                    ImageLoader.getInstance().displayImage(
                            "file://" + info.getPostInfo().videoCover, holder.icon);
                }
            }
        }

        @Override
        public void progress(int progress) {
            holder.progressBar.setProgress(progress);
        }

        @Override
        public void pause() {}

        @Override
        public void error(String msg) {
            holder.plan.setText("");
            resetSendState(holder, false);
        }

        @Override
        public void cancel() {}
    }

    private ViewHolder[] holders;

    class ViewHolder {
        View container;
        ImageView icon;
        TextView plan;
        TextView name;
        ImageView btnUpload;
        CircularProgressButton progressBar;
    }

    class RefreshBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            loadDatas();
        }
    }

    @Override
    public void onDestroy() {
        if (refreshBroadCast != null && getActivity() != null)
            getActivity().unregisterReceiver(refreshBroadCast);
        super.onDestroy();
    }

}
